using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using WIT.DAQ.Core.Models;
using WIT.DAQ.Core.Properties;

namespace WIT.DAQ.Core.Forms;

/// <summary>
///
/// </summary>
internal class LogViewForm : BaseForm
{
	/// <summary>
	/// 是否显示任务执行时长
	/// </summary>
	private bool ShowTaskDuration = false;

	/// <summary>
	/// 是否过滤任务执行时长
	/// </summary>
	private bool FilterDuration = false;

	/// <summary>
	/// 过滤条件-执行时长（s）
	/// </summary>
	private decimal Duration = 0.0m;

	/// <summary>
	/// Required designer variable.
	/// </summary>
	private IContainer components = null;

	private Button btnQuery;

	private Label label1;

	private ComboBox cmbStations;

	private DateTimePicker dtpStart;

	private DateTimePicker dtpEnd;

	private Label label2;

	private Label label3;

	private TreeView tvProcesses;

	private RichTextBox txtDetails;

	private Label label4;

	private Label lblLogCount;

	private ImageList imageList;

	private SplitContainer splitContainer1;

	private Label label5;

	private ComboBox cmbTasks;

	private Panel pnlDetail;

	private Button btnSetting;

	private Button btnAdvancedQuery;

	/// <summary>
	///
	/// </summary>
	internal LogViewForm()
	{
		InitializeComponent();
		InitStations();
	}

	private void LogViewForm_Load(object sender, EventArgs e)
	{
		ToolTip toolTip = new ToolTip();
		toolTip.AutoPopDelay = 3000;
		toolTip.InitialDelay = 500;
		toolTip.ReshowDelay = 500;
		toolTip.ShowAlways = true;
		toolTip.SetToolTip(btnSetting, "查询设置");
		ToolTip toolTip2 = new ToolTip();
		toolTip2.AutoPopDelay = 3000;
		toolTip2.InitialDelay = 500;
		toolTip2.ReshowDelay = 500;
		toolTip2.ShowAlways = true;
		toolTip2.SetToolTip(btnAdvancedQuery, "模糊查询");
		dtpStart.Value = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
		dtpEnd.Value = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:59"));
	}

	/// <summary>
	/// 加载站点
	/// </summary>
	private void InitStations()
	{
		List<Station> allStations = Common.GetAllStations();
		allStations.Insert(0, new Station
		{
			Id = new Guid("00000000-0000-0000-0000-000000000001"),
			Name = "Socket服务"
		});
		allStations.Insert(0, new Station
		{
			Id = default(Guid),
			Name = string.Empty
		});
		cmbStations.DataSource = allStations;
		cmbStations.DisplayMember = "Name";
		cmbStations.ValueMember = "Id";
		cmbStations.SelectedIndex = 0;
		cmbStations.SelectedIndexChanged += cmbStations_SelectedIndexChanged;
	}

	/// <summary>
	/// 切换站点时，加载任务列表
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void cmbStations_SelectedIndexChanged(object sender, EventArgs e)
	{
		if (cmbStations.SelectedItem == null)
		{
			return;
		}
		Guid guid = (Guid)cmbStations.SelectedValue;
		if (guid != default(Guid) && guid != new Guid("00000000-0000-0000-0000-000000000001"))
		{
			List<DAQTask> dAQTasks = Common.GetDAQTasks(guid);
			if (dAQTasks != null)
			{
				dAQTasks.Insert(0, new DAQTask
				{
					Id = default(Guid),
					Name = string.Empty
				});
				cmbTasks.DataSource = dAQTasks;
				cmbTasks.DisplayMember = "Name";
				cmbTasks.ValueMember = "Id";
				cmbTasks.SelectedIndex = 0;
			}
		}
		else
		{
			cmbTasks.DataSource = null;
		}
	}

	/// <summary>
	/// 查询
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void btnQuery_Click(object sender, EventArgs e)
	{
		Guid? guid = null;
		if (cmbStations.SelectedItem != null)
		{
			guid = (Guid)cmbStations.SelectedValue;
		}
		Guid? taskId = null;
		if (cmbTasks.SelectedItem != null)
		{
			taskId = (Guid)cmbTasks.SelectedValue;
		}
		tvProcesses.Nodes.Clear();
		lblLogCount.Text = "0";
		txtDetails.ResetText();
		DataTable dataTable = null;
		if (guid.HasValue && guid == new Guid("00000000-0000-0000-0000-000000000001"))
		{
			string name = ((Station)cmbStations.SelectedItem).Name;
			dataTable = Common.QueryLogProcesses(name, string.Empty, dtpStart.Value, dtpEnd.Value, Common.LOG_LIMITCOUNT, FilterDuration, Duration);
		}
		else
		{
			dataTable = Common.QueryLogProcesses(guid, taskId, dtpStart.Value, dtpEnd.Value, Common.LOG_LIMITCOUNT, FilterDuration, Duration);
		}
		ShowLogs(dataTable);
	}

	/// <summary>
	/// 查询设置
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void btnSetting_Click(object sender, EventArgs e)
	{
		LogSettingForm logSettingForm = new LogSettingForm(ShowTaskDuration, FilterDuration, Duration)
		{
			Icon = base.Icon,
			StartPosition = FormStartPosition.CenterParent
		};
		logSettingForm.SaveLogSetting += LogSettingForm_SaveLogSetting;
		logSettingForm.ShowDialog();
	}

	/// <summary>
	/// 查询设置-确定
	/// </summary>
	/// <param name="showTaskDuration"></param>
	/// <param name="filterDuration"></param>
	/// <param name="duration"></param>
	private void LogSettingForm_SaveLogSetting(bool showTaskDuration, bool filterDuration, decimal duration)
	{
		ShowTaskDuration = showTaskDuration;
		FilterDuration = filterDuration;
		Duration = duration;
	}

	/// <summary>
	/// 高级查询
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void btnAdvancedQuery_Click(object sender, EventArgs e)
	{
		Log_AdvancedQueryForm log_AdvancedQueryForm = new Log_AdvancedQueryForm
		{
			Icon = base.Icon,
			StartPosition = FormStartPosition.CenterParent
		};
		log_AdvancedQueryForm.AdvancedQuery += Log_AdvancedQueryForm_AdvancedQuery;
		log_AdvancedQueryForm.ShowDialog();
	}

	/// <summary>
	/// 高级查询-确定
	/// </summary>
	/// <param name="fuzzyContent"></param>
	private void Log_AdvancedQueryForm_AdvancedQuery(string fuzzyContent)
	{
		if (string.IsNullOrEmpty(fuzzyContent))
		{
			MessageBox.Show("模糊查询界面中未输入任何查询条件");
			return;
		}
		tvProcesses.Nodes.Clear();
		lblLogCount.Text = "0";
		txtDetails.ResetText();
		DataTable dt = Common.QueryLogProcesses(fuzzyContent, Common.LOG_LIMITCOUNT, FilterDuration, Duration);
		ShowLogs(dt);
	}

	/// <summary>
	/// 将查询到的日志主记录显示在Tree中
	/// </summary>
	/// <param name="dt"></param>
	private void ShowLogs(DataTable dt)
	{
		if (dt == null || dt.Rows.Count <= 0)
		{
			return;
		}
		if (dt.Rows.Count > Common.LOG_LIMITCOUNT)
		{
			lblLogCount.Text = $"> {Common.LOG_LIMITCOUNT}";
		}
		else
		{
			lblLogCount.Text = dt.Rows.Count.ToString();
		}
		foreach (DataRow row in dt.Rows)
		{
			TreeNode treeNode = new TreeNode
			{
				Name = row["id"].ToString(),
				Tag = row["duration"].ToString(),
				Checked = Convert.ToBoolean(row["already_read"])
			};
			if (ShowTaskDuration)
			{
				string text = ((!string.IsNullOrEmpty(row["duration"].ToString())) ? (Convert.ToDecimal(row["duration"]).ToString("0.00") + "s") : "未统计");
				treeNode.Text = string.Format("[{0}] - [{1}] [{2}] {3}", text, Convert.ToDateTime(row["create_time"]).ToString("MM-dd HH:mm:ss"), row["station_name"], row["task_name"]);
			}
			else
			{
				treeNode.Text = string.Format("[{0}] [{1}] {2}", Convert.ToDateTime(row["create_time"]).ToString("MM-dd HH:mm:ss"), row["station_name"], row["task_name"]);
			}
			if (treeNode.Checked)
			{
				treeNode.ImageIndex = 1;
				treeNode.SelectedImageIndex = 1;
			}
			else
			{
				treeNode.ImageIndex = 0;
				treeNode.SelectedImageIndex = 0;
			}
			tvProcesses.Nodes.Add(treeNode);
		}
	}

	/// <summary>
	/// 查看日志明细
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tvProcesses_AfterSelect(object sender, TreeViewEventArgs e)
	{
		txtDetails.ResetText();
		string errMsg;
		DataTable dataTable = Common.QueryLogDetails(Convert.ToInt32(tvProcesses.SelectedNode.Name), out errMsg);
		if (dataTable == null)
		{
			txtDetails.AppendText("查询日志明细时失败：\r" + errMsg);
		}
		else if (dataTable.Rows.Count == 0)
		{
			txtDetails.AppendText("no data.");
		}
		else
		{
			string value = e.Node.Tag.ToString();
			if (!string.IsNullOrEmpty(value))
			{
				txtDetails.AppendText("耗时共计：" + Convert.ToDecimal(value).ToString("0.000") + " 秒");
			}
			else
			{
				txtDetails.AppendText("未统计耗时");
			}
			txtDetails.AppendText("\r");
			txtDetails.AppendText("\r");
			foreach (DataRow row in dataTable.Rows)
			{
				txtDetails.AppendText("===== " + Convert.ToDateTime(row["create_time"]).ToString("yyyy/MM/dd HH:mm:ss.fff") + " =====");
				txtDetails.AppendText("\r");
				txtDetails.AppendText(row["content"].ToString());
				txtDetails.AppendText("\r");
				txtDetails.AppendText("\r");
			}
		}
		if (!Convert.ToBoolean(tvProcesses.SelectedNode.Checked) && Common.AlreadyRead(Convert.ToInt32(tvProcesses.SelectedNode.Name)))
		{
			tvProcesses.SelectedNode.Checked = true;
			tvProcesses.SelectedNode.ImageIndex = 1;
			tvProcesses.SelectedNode.SelectedImageIndex = 1;
		}
	}

	/// <summary>
	/// Clean up any resources being used.
	/// </summary>
	/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
	protected override void Dispose(bool disposing)
	{
		if (disposing && components != null)
		{
			components.Dispose();
		}
		base.Dispose(disposing);
	}

	/// <summary>
	/// Required method for Designer support - do not modify
	/// the contents of this method with the code editor.
	/// </summary>
	private void InitializeComponent()
	{
		this.components = new System.ComponentModel.Container();
		System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WIT.DAQ.Core.Forms.LogViewForm));
		this.btnQuery = new System.Windows.Forms.Button();
		this.label1 = new System.Windows.Forms.Label();
		this.cmbStations = new System.Windows.Forms.ComboBox();
		this.dtpStart = new System.Windows.Forms.DateTimePicker();
		this.dtpEnd = new System.Windows.Forms.DateTimePicker();
		this.label2 = new System.Windows.Forms.Label();
		this.label3 = new System.Windows.Forms.Label();
		this.tvProcesses = new System.Windows.Forms.TreeView();
		this.imageList = new System.Windows.Forms.ImageList(this.components);
		this.txtDetails = new System.Windows.Forms.RichTextBox();
		this.label4 = new System.Windows.Forms.Label();
		this.lblLogCount = new System.Windows.Forms.Label();
		this.splitContainer1 = new System.Windows.Forms.SplitContainer();
		this.pnlDetail = new System.Windows.Forms.Panel();
		this.label5 = new System.Windows.Forms.Label();
		this.cmbTasks = new System.Windows.Forms.ComboBox();
		this.btnSetting = new System.Windows.Forms.Button();
		this.btnAdvancedQuery = new System.Windows.Forms.Button();
		((System.ComponentModel.ISupportInitialize)this.splitContainer1).BeginInit();
		this.splitContainer1.Panel1.SuspendLayout();
		this.splitContainer1.Panel2.SuspendLayout();
		this.splitContainer1.SuspendLayout();
		this.pnlDetail.SuspendLayout();
		base.SuspendLayout();
		this.btnQuery.Location = new System.Drawing.Point(418, 39);
		this.btnQuery.Name = "btnQuery";
		this.btnQuery.Size = new System.Drawing.Size(80, 46);
		this.btnQuery.TabIndex = 7;
		this.btnQuery.Text = "查询(&Q)";
		this.btnQuery.UseVisualStyleBackColor = true;
		this.btnQuery.Click += new System.EventHandler(btnQuery_Click);
		this.label1.AutoSize = true;
		this.label1.Font = new System.Drawing.Font("宋体", 9f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 134);
		this.label1.Location = new System.Drawing.Point(36, 42);
		this.label1.Name = "label1";
		this.label1.Size = new System.Drawing.Size(41, 12);
		this.label1.TabIndex = 8;
		this.label1.Text = "站点：";
		this.cmbStations.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
		this.cmbStations.Font = new System.Drawing.Font("宋体", 9f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 134);
		this.cmbStations.FormattingEnabled = true;
		this.cmbStations.Location = new System.Drawing.Point(83, 39);
		this.cmbStations.Name = "cmbStations";
		this.cmbStations.Size = new System.Drawing.Size(329, 20);
		this.cmbStations.TabIndex = 6;
		this.dtpStart.CustomFormat = "yyyy/MM/dd HH:mm:ss";
		this.dtpStart.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
		this.dtpStart.Location = new System.Drawing.Point(83, 12);
		this.dtpStart.Name = "dtpStart";
		this.dtpStart.Size = new System.Drawing.Size(153, 21);
		this.dtpStart.TabIndex = 9;
		this.dtpEnd.CustomFormat = "yyyy/MM/dd HH:mm:ss";
		this.dtpEnd.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
		this.dtpEnd.Location = new System.Drawing.Point(259, 12);
		this.dtpEnd.Name = "dtpEnd";
		this.dtpEnd.Size = new System.Drawing.Size(153, 21);
		this.dtpEnd.TabIndex = 9;
		this.label2.AutoSize = true;
		this.label2.Font = new System.Drawing.Font("宋体", 9f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 134);
		this.label2.Location = new System.Drawing.Point(242, 18);
		this.label2.Name = "label2";
		this.label2.Size = new System.Drawing.Size(11, 12);
		this.label2.TabIndex = 8;
		this.label2.Text = "-";
		this.label3.AutoSize = true;
		this.label3.Font = new System.Drawing.Font("宋体", 9f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 134);
		this.label3.Location = new System.Drawing.Point(12, 18);
		this.label3.Name = "label3";
		this.label3.Size = new System.Drawing.Size(65, 12);
		this.label3.TabIndex = 8;
		this.label3.Text = "时间范围：";
		this.tvProcesses.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right;
		this.tvProcesses.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
		this.tvProcesses.ImageIndex = 0;
		this.tvProcesses.ImageList = this.imageList;
		this.tvProcesses.ItemHeight = 15;
		this.tvProcesses.Location = new System.Drawing.Point(0, 0);
		this.tvProcesses.Name = "tvProcesses";
		this.tvProcesses.SelectedImageIndex = 0;
		this.tvProcesses.ShowNodeToolTips = true;
		this.tvProcesses.Size = new System.Drawing.Size(450, 538);
		this.tvProcesses.TabIndex = 10;
		this.tvProcesses.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(tvProcesses_AfterSelect);
		this.imageList.ImageStream = (System.Windows.Forms.ImageListStreamer)resources.GetObject("imageList.ImageStream");
		this.imageList.TransparentColor = System.Drawing.Color.Transparent;
		this.imageList.Images.SetKeyName(0, "circle-grey.png");
		this.imageList.Images.SetKeyName(1, "circle-green.png");
		this.imageList.Images.SetKeyName(2, "circle-red.png");
		this.imageList.Images.SetKeyName(3, "circle_yellow.png");
		this.txtDetails.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right;
		this.txtDetails.BorderStyle = System.Windows.Forms.BorderStyle.None;
		this.txtDetails.Location = new System.Drawing.Point(3, 3);
		this.txtDetails.Name = "txtDetails";
		this.txtDetails.ReadOnly = true;
		this.txtDetails.Size = new System.Drawing.Size(778, 553);
		this.txtDetails.TabIndex = 11;
		this.txtDetails.Text = "";
		this.label4.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left;
		this.label4.AutoSize = true;
		this.label4.Font = new System.Drawing.Font("宋体", 9f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 134);
		this.label4.Location = new System.Drawing.Point(3, 542);
		this.label4.Name = "label4";
		this.label4.Size = new System.Drawing.Size(53, 12);
		this.label4.TabIndex = 8;
		this.label4.Text = "日志数量";
		this.lblLogCount.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left;
		this.lblLogCount.AutoSize = true;
		this.lblLogCount.Font = new System.Drawing.Font("宋体", 9f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 134);
		this.lblLogCount.Location = new System.Drawing.Point(62, 542);
		this.lblLogCount.Name = "lblLogCount";
		this.lblLogCount.Size = new System.Drawing.Size(11, 12);
		this.lblLogCount.TabIndex = 8;
		this.lblLogCount.Text = "0";
		this.splitContainer1.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right;
		this.splitContainer1.Location = new System.Drawing.Point(12, 91);
		this.splitContainer1.Name = "splitContainer1";
		this.splitContainer1.Panel1.Controls.Add(this.tvProcesses);
		this.splitContainer1.Panel1.Controls.Add(this.label4);
		this.splitContainer1.Panel1.Controls.Add(this.lblLogCount);
		this.splitContainer1.Panel1MinSize = 300;
		this.splitContainer1.Panel2.Controls.Add(this.pnlDetail);
		this.splitContainer1.Size = new System.Drawing.Size(1240, 558);
		this.splitContainer1.SplitterDistance = 450;
		this.splitContainer1.TabIndex = 12;
		this.pnlDetail.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
		this.pnlDetail.Controls.Add(this.txtDetails);
		this.pnlDetail.Dock = System.Windows.Forms.DockStyle.Fill;
		this.pnlDetail.Location = new System.Drawing.Point(0, 0);
		this.pnlDetail.Name = "pnlDetail";
		this.pnlDetail.Size = new System.Drawing.Size(786, 558);
		this.pnlDetail.TabIndex = 12;
		this.label5.AutoSize = true;
		this.label5.Font = new System.Drawing.Font("宋体", 9f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 134);
		this.label5.Location = new System.Drawing.Point(36, 68);
		this.label5.Name = "label5";
		this.label5.Size = new System.Drawing.Size(41, 12);
		this.label5.TabIndex = 14;
		this.label5.Text = "任务：";
		this.cmbTasks.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
		this.cmbTasks.Font = new System.Drawing.Font("宋体", 9f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 134);
		this.cmbTasks.FormattingEnabled = true;
		this.cmbTasks.Location = new System.Drawing.Point(83, 65);
		this.cmbTasks.Name = "cmbTasks";
		this.cmbTasks.Size = new System.Drawing.Size(329, 20);
		this.cmbTasks.TabIndex = 13;
		this.btnSetting.BackgroundImage = global::WIT_DAQ_Core_Properties_Resour.setting;
		this.btnSetting.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
		this.btnSetting.ImageAlign = System.Drawing.ContentAlignment.TopLeft;
		this.btnSetting.Location = new System.Drawing.Point(504, 60);
		this.btnSetting.Name = "btnSetting";
		this.btnSetting.Size = new System.Drawing.Size(25, 25);
		this.btnSetting.TabIndex = 16;
		this.btnSetting.UseVisualStyleBackColor = true;
		this.btnSetting.Click += new System.EventHandler(btnSetting_Click);
		this.btnAdvancedQuery.Location = new System.Drawing.Point(418, 11);
		this.btnAdvancedQuery.Name = "btnAdvancedQuery";
		this.btnAdvancedQuery.Size = new System.Drawing.Size(80, 23);
		this.btnAdvancedQuery.TabIndex = 17;
		this.btnAdvancedQuery.Text = "模糊查询";
		this.btnAdvancedQuery.UseVisualStyleBackColor = true;
		this.btnAdvancedQuery.Click += new System.EventHandler(btnAdvancedQuery_Click);
		base.AutoScaleDimensions = new System.Drawing.SizeF(6f, 12f);
		base.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
		base.ClientSize = new System.Drawing.Size(1264, 661);
		base.Controls.Add(this.btnAdvancedQuery);
		base.Controls.Add(this.cmbStations);
		base.Controls.Add(this.btnQuery);
		base.Controls.Add(this.label5);
		base.Controls.Add(this.cmbTasks);
		base.Controls.Add(this.splitContainer1);
		base.Controls.Add(this.dtpEnd);
		base.Controls.Add(this.dtpStart);
		base.Controls.Add(this.label2);
		base.Controls.Add(this.label3);
		base.Controls.Add(this.label1);
		base.Controls.Add(this.btnSetting);
		base.Name = "LogViewForm";
		this.Text = "查看日志";
		base.Load += new System.EventHandler(LogViewForm_Load);
		this.splitContainer1.Panel1.ResumeLayout(false);
		this.splitContainer1.Panel1.PerformLayout();
		this.splitContainer1.Panel2.ResumeLayout(false);
		((System.ComponentModel.ISupportInitialize)this.splitContainer1).EndInit();
		this.splitContainer1.ResumeLayout(false);
		this.pnlDetail.ResumeLayout(false);
		base.ResumeLayout(false);
		base.PerformLayout();
	}
}
